package one.stand.controller.supplier;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.dto.AiCustomerRequest;
import com.jmp.api.dto.AiCustomerResponse;
import com.jmp.api.dto.AiTimeHideRequest;
import com.jmp.api.dto.AiTimeResponse;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.dto.SeeRecordHideDto;
import com.jmp.feign.SeeRecordFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageRequest;
import one.stand.dto.PageResponse2;
import one.stand.dto.UserDto;
import one.stand.enums.SeeRecordEnums;
import one.stand.mapper.ArticleMapper;
import one.stand.mapper.SeeRecordApiCrmAppMapper;
import one.stand.mapper.SeeRecordPublicMapper;
import one.stand.model.*;
import one.stand.response.CustomerAnalysisResponse;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.GoodsBaseService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.OneListUtil;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@Api(description = "AI追踪")
@RestController
@RequestMapping("/ai")
public class AiRecordController {

    @Autowired
    private SeeRecordFeign seeRecordFeign;

    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private SeeRecordPublicMapper seeRecordPublicMapper;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;

    @Autowired
    private SeeRecordApiCrmAppMapper seeRecordApiCrmMapper;

    @ApiOperation("1时间追踪")
    @GetMapping("time")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<AiTimeResponse> time(@RequestAttribute PageRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CrmSeeRecordModel> crmSeeRecordModels = seeRecordApiCrmMapper.selectUserAll(optUser.getCardId());

        PageResponse2<AiTimeResponse.Record> recordPage = ConvertUtils.page2(crmSeeRecordModels, c -> {
            String userName = null;
            String userImg = null;
            Integer userId = null;
            if (Objects.nonNull(c.getUserId())) {
                userId = c.getUserId().intValue();
                UserDto user = userAdminService.get(userId);
                userImg = user.getUserImg();
                userName = user.getName();
            }

            String targetName = null;
            if (SeeRecordEnums.PRODUCT.getCode().equals(c.getSeeType())) {
                Goods goods = goodsBaseService.get(c.getItmeId());
                if (Objects.nonNull(goods)) {
                    targetName = goods.getGoodsName();
                }
            } else if (SeeRecordEnums.LEAD.getCode().equals(c.getSeeType())) {
                Article article = articleMapper.selectByPrimaryKey(c.getItmeId());
                if (Objects.nonNull(article)) {
                    targetName = article.getTitle();
                }
            }

            String typeName = SeeRecordEnums.getByCode(c.getSeeType()).getMessage();
            if (StringUtils.isNoneBlank(targetName)) {
                typeName = typeName + ": " + targetName;
            }

            return AiTimeResponse.Record.builder()
                    .time(c.getCreateTime().getTime())
                    .userId(userId)
                    .userImg(userImg)
                    .userName(userName)
                    .newVisitor(BooleanUtils.toInteger(c.getRanking() <= 1))
                    .content("该用户正在查看您的" + typeName + "，累计与您互动" + c.getRanking() + "次")
                    .contentHighlight(Lists.newArrayList(typeName, String.valueOf(c.getRanking())))
                    .build();
        });

        AiTimeResponse response = AiTimeResponse.builder()
                .recordPage(recordPage)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("1隐藏")
    @PostMapping("time/hide")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel timeHide(@RequestAttribute AiTimeHideRequest request) {
        AssertUtil.nonNull(request.getUserId(), ResultEnum.PARAM_CHECK);
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        ResultModel resultModel = seeRecordFeign.hide(SeeRecordHideDto.builder()
                .cardId(optUser.getCardId())
                .viewUserId(request.getUserId())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation("2客户分析")
    @PostMapping("customer")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<AiCustomerResponse> customer(@RequestAttribute AiCustomerRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CrmSeeRecordModel> crmSeeRecordModels = seeRecordApiCrmMapper.getCrmSeeRecord(request.getUserId(), Objects.nonNull(request.getCardId()) ? request.getCardId() : optUser.getCardId());

        PageResponse2<AiCustomerResponse.Record> recordPage = ConvertUtils.page2(crmSeeRecordModels, crmSeeRecordModel -> {
            String content;
            if (SeeRecordEnums.CARD.getCode().equals(crmSeeRecordModel.getSeeType())) {
                content = "Ta正在查看名片第" + crmSeeRecordModel.getRanking() + "次，现在沟通，效率更高哦";
            } else if (SeeRecordEnums.OFFICIAL_WEBSITE.getCode().equals(crmSeeRecordModel.getSeeType())) {
                content = "Ta正在查看官网第" + crmSeeRecordModel.getRanking() + "次，有望合作";
            } else if (SeeRecordEnums.ARTICLE.getCode().equals(crmSeeRecordModel.getSeeType())) {
                content = "Ta正在查看动态第" + crmSeeRecordModel.getRanking() + "次，合作意向很强烈";
            } else if (SeeRecordEnums.PRODUCT.getCode().equals(crmSeeRecordModel.getSeeType())) {
                String targetName;
                if (Objects.isNull(crmSeeRecordModel.getItmeId())) {
                    targetName = "产品列表";
                } else {
                    Goods goods = goodsBaseService.get(crmSeeRecordModel.getItmeId());
                    if (Objects.nonNull(goods)) {
                        targetName = goods.getGoodsName() + "产品";
                    } else {
                        targetName = "产品";
                    }
                }
                content = "Ta正在查看" + targetName + "，累计查看产品" + crmSeeRecordModel.getRanking() + "次，尽快把握商机。";
            } else if (SeeRecordEnums.LEAD.getCode().equals(crmSeeRecordModel.getSeeType())) {
                content = "Ta正在查看头条文章第" + crmSeeRecordModel.getRanking() + "次";
            } else {
                content = StringUtils.EMPTY;
            }
            return AiCustomerResponse.Record.builder()
                    .targetName(content)
                    .time(crmSeeRecordModel.getCreateTime().getTime())
                    .build();
        });

        //客户信息
        AiCustomerResponse.UserInfo userInfo = null;
        if (request.getPageNum() == 1) {

            UserDto user = userAdminService.get(request.getUserId());
            if (!user.isEmptyUser()) {
                String content = null;
                List<String> contentHighlight = Lists.newArrayList();
                if (OneListUtil.isNotEmpty(crmSeeRecordModels)) {
                    String targetName = null;
                    if (SeeRecordEnums.PRODUCT.getCode().equals(crmSeeRecordModels.get(0).getSeeType())) {
                        Goods goods = goodsBaseService.get(crmSeeRecordModels.get(0).getItmeId());
                        if (Objects.nonNull(goods)) {
                            targetName = goods.getGoodsName();
                        }
                    } else if (SeeRecordEnums.LEAD.getCode().equals(crmSeeRecordModels.get(0).getSeeType())) {
                        Article article = articleMapper.selectByPrimaryKey(crmSeeRecordModels.get(0).getItmeId());
                        if (Objects.nonNull(article)) {
                            targetName = article.getTitle();
                        }
                    }
                    String typeName = SeeRecordEnums.getByCode(crmSeeRecordModels.get(0).getSeeType()).getMessage();
                    if (StringUtils.isNoneBlank(targetName)) {
                        typeName = typeName + ": " + targetName;
                    }
                    content = "该用户正在查看您的" + typeName + "，累计与您互动" + crmSeeRecordModels.get(0).getRanking() + "次";
                    contentHighlight = Lists.newArrayList(typeName, String.valueOf(crmSeeRecordModels.get(0).getRanking()));
                }

                CustomerAnalysisResponse analysisModel = seeRecordPublicMapper.getCustomerAnalysis(optUser.getCardId(), request.getUserId(), SeeRecordEnums.PRODUCT.getCode(), optUser.getCompanyId());

                BusinessCard card = businessCardBaseService.getByUserId(request.getUserId());
                String wx = null;
                String phone = user.getPhone();
                if (Objects.nonNull(card)) {
                    wx = card.getPersonalWx();
                    phone = card.getPhone();
                }

                userInfo = AiCustomerResponse.UserInfo.builder()
                        .userName(user.getName())
                        .userImg(user.getUserImg())
                        .content(content)
                        .contentHighlight(contentHighlight)
                        .rate(analysisModel.getRate())

                        .chatId(user.getUserId())
                        .phone(phone)
                        .personalWx(wx)
                        .build();
            }
        }

        AiCustomerResponse response = AiCustomerResponse.builder()
                .recordPage(recordPage)
                .userInfo(userInfo)
                .build();
        return ResultModel.success(response);
    }
}
